<template>
  <div>
    <FilterTree
      ref="filterTree"
      :treeData="baseTree"
      :highTreeData="highParamTree"
      @updateParams="updateParams"
      :searchPlaceholder="'请输入昵称/手机号'"
      @updateSearchText="updateSearchText"
      :showRootArray="false"
      :showHighest="true"
    ></FilterTree>
    <a-divider dashed style="margin-top:12px;" />
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <!-- <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="手机号/昵称">
            <a-input v-model="queryParam.phone" placeholder="请输入" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="注册时间" has-feedback>
            <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.regTime" @change="onChange" @ok="onOk" />
          </a-form-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="订阅时间" has-feedback>
            <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.subStartTime" @change="onChange" @ok="onOk" />
          </a-form-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="订阅到期时间" has-feedback>
            <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.subEndTime" @change="onChange" @ok="onOk" />
          </a-form-item>
        </a-col> -->
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
            <a-form-item label="排序">
              <a-select v-model="queryParam.sortType" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="handleChange">
                <a-select-option :value="1">订阅时间倒序</a-select-option>
                <a-select-option :value="2">累计消费金额从高到低</a-select-option>
                <a-select-option :value="3">会员积分降序</a-select-option>
                <!-- 1 要盒时间倒序 2 累计消费金额从高到低 3 会员积分降序 -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24" style="min-height: 56px;">
            <!-- <a-form-item label="剩余BOX">
              <a-input-number :min="0" :step="1" @change="lPriceChange" placeholder="最低数" v-model="queryParam.remainMin" /> ~
              <a-input-number :min="0" :max="99" :step="1" @change="gPriceChange" placeholder="最高数" v-model="queryParam.remainMax" />
            </a-form-item> -->
            <RankPrice :label="'剩余BOX'" @updateRank="updateRank" :lowConfig="{ min: 0, max: 99, step: 1 }" :highConfig="{ min: 0, max: 99, step: 1 }"></RankPrice>
          </a-col>
          <!-- <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="订阅状态">
            <a-select v-model="queryParam.subStatus" placeholder="请选择">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="item.code" v-for="item in filter.subStatus" :key="item.code">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="性别">
            <a-select v-model="queryParam.gender" placeholder="请选择">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="item.code" v-for="item in filter.gender" :key="item.code">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
            <a-form-item label="有可用生日折扣券">
              <a-switch default-checked @change="switchChange" v-model="queryParam.isBirthday" />
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24" v-has="'customerList:notFashioner'">
            <a-form-item label="搭配师类型">
              <a-select v-model="queryParam.fashionerType" placeholder="请选择" @change="handleChangeType">
                <a-select-option value="">全部</a-select-option>
                <a-select-option :value="item.code" v-for="item in filter.fashionerType" :key="item.code">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24" v-if="queryParam.fashionerType === '0'" v-has="'customerList:notFashioner'">
            <a-form-item label="搭配师">
              <a-select v-model="queryParam.fashionerId" placeholder="请选择" show-search :filter-option="filterOption" :allowClear="true" @change="handleChange">
                <a-select-option value="">全部</a-select-option>
                <a-select-option :value="item.code" v-for="item in filter.fashioner" :key="item.code">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24" v-if="queryParam.fashionerType == 1" v-has="'customerList:notFashioner'">
            <a-form-item label="导购手机号">
              <a-input v-model="queryParam.salesPhone" placeholder="请输入" :allowClear="true" @keyup.enter="searchSalesPhone" @change="onChangePhone" ref="salesPhone" />
            </a-form-item>
          </a-col>

          <!-- <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="会员卡等级">
            <a-select v-model="queryParam.vipType" placeholder="请选择">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="item.code" v-for="item in filter.vipType" :key="item.code">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
          <!-- <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-item label="会员标签">
            <a-select mode="multiple" option-label-prop="label" v-model="queryParam.tags" placeholder="请选择">
              <a-select-option value="白金卡" label="白金卡">白金卡</a-select-option>
              <a-select-option value="金卡" label="金卡">金卡</a-select-option>
              <a-select-option value="银卡" label="银卡">银卡</a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
          <template v-if="black">
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="黑名单原因">
                <a-select v-model="queryParam.reasonId" placeholder="请选择" show-search :filter-option="filterOption" @change="handleChange">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option :value="item.code" v-for="item in filter.blackListReason" :key="item.code">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="加入黑名单时间" has-feedback>
                <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.joinTime" @change="onChange" @ok="onOk" />
              </a-form-item>
            </a-col>
          </template>
          <template v-if="special">
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="特殊原因">
                <a-select v-model="queryParam.reasonId" placeholder="请选择" show-search :filter-option="filterOption" @change="handleChange">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option :value="item.code" v-for="item in filter.specialListReason" :key="item.code">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="加入特殊名单时间" has-feedback>
                <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.joinTime" @change="onChange" @ok="onOk" />
              </a-form-item>
            </a-col>
          </template>
          <!-- <a-col :xxl="black || special ? 24 : 12" :xl="black || special ? 24 : 16" :lg="black || special ? 24 : 24" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              <a-button style="margin-left: 8px">导出</a-button>
              <a-dropdown v-if="selectedRowKeys.length > 0">
                <a-menu slot="overlay">
                  <a-menu-item key="1" @click="showModal('swap', true)"><a-icon type="swap" />变更搭配师</a-menu-item>
                  <a-menu-item key="2" v-if="special" @click="handleRemove('special')"><a-icon type="minus" />移出特殊名单</a-menu-item>
                  <a-menu-item key="3" v-if="black" @click="handleRemove('black')"><a-icon type="minus" />移出黑名单</a-menu-item>
                  <a-menu-item key="4" v-if="!black && !special" @click="showModal('joinS', true)"><a-icon type="plus" />加入特殊名单</a-menu-item>
                  <a-menu-item key="5" v-if="!black" @click="showModal('joinB', true)"><a-icon type="plus" />加入黑名单</a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
              </a-dropdown>
              <a-button style="margin-left: 8px" v-else @click="batchControl"> 批量操作 </a-button>
            </span>
          </a-col> -->
        </a-row>
      </a-form>
      <a-modal title="温馨提示" :dialog-style="{ top: '20px' }" :visible="removeVisible" @ok="() => removeOk()" @cancel="() => (removeVisible = false)">
        <p>{{ remveText }}</p>
      </a-modal>
    </div>
    <a-divider dashed style="margin-top:8px;" />
    <a-row>
      <a-col :xxl="24" :xl="24" :lg="24" :sm="24">
        <span class="table-page-search-submitButtons">
          <a-dropdown :disabled="!(selectedRowKeys.length > 0)">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="showModal('swap', true)"><a-icon type="swap" />变更搭配师</a-menu-item>
              <template v-if="allowSB">
                <a-menu-item key="2" v-if="special" @click="handleRemove('special')"><a-icon type="minus" />移出特殊名单</a-menu-item>
                <a-menu-item key="3" v-if="black" @click="handleRemove('black')"><a-icon type="minus" />移出黑名单</a-menu-item>
                <a-menu-item key="4" v-if="!black && !special" @click="showModal('joinS', true)"><a-icon type="plus" />加入特殊名单</a-menu-item>
                <a-menu-item key="5" v-if="!black" @click="showModal('joinB', true)"><a-icon type="plus" />加入黑名单</a-menu-item>
              </template>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
          </a-dropdown>
        </span>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import { batchJoinCategory } from '@/api/box/member.js'
import { USER_AUTH } from '@/store/mutation-types'
import FilterTree from '@/views/box/components/FilterTree'
import RankPrice from '@/views/box/components/rankPrice'
export default {
  props: {
    filter: {
      type: Object,
      default: {}
    },
    paramTree: {
      type: Array
    },
    selectedRowKeys: {
      type: Array,
      default: null
    },
    black: {
      type: Boolean,
      default: false
    },
    special: {
      type: Boolean,
      default: false
    },
    selectedRows: {
      type: Array,
      default: []
    },
    allowSB: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  components: {
    FilterTree,
    RankPrice
  },
  data() {
    return {
      // 查询参数
      queryParam: {
        // subStatus: '',
        // gender: '',
        fashionerId: '',
        // vipType: '',
        fashionerType: this.filter.fashionerType ? this.filter.fashionerType.filter(e => e.default)[0].code : null,
        reasonId: '',
        sortType: 1,
        salesPhone: '',
        isBirthday: false
      },
      removeVisible: false,
      remveText: '',
      removeType: '',
      authList: [],
      isFashioner: null,
      baseTree: [],
      highParamTree: [],
      tree: []
    }
  },
  watch: {
    'filter.fashionerType': function(newVal, oldVal) {
      this.queryParam.fashionerType = newVal.filter(e => e.default)[0].code || ''
    },
    paramTree(val) {
      this.tree = JSON.parse(JSON.stringify(val))
      this.getTree()
    }
  },
  created() {
    this.authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')
    if (this.authList.filter(e => e.action == 'customerList:notFashioner').length > 0) {
      this.isFashioner = false
    } else {
      this.isFashioner = true
    }
  },
  mounted() {
    this.tree = JSON.parse(JSON.stringify(this.paramTree))
    this.getTree()
  },
  methods: {
    getTree() {
      this.baseTree = this.tree.slice(0, 3)
      this.highParamTree = this.tree.slice(3)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    removeOk() {
      // if (this.removeType) return
      let data = {
        requestData: {
          customerIds: this.selectedRows,
          categoryId: 56
        }
      }
      batchJoinCategory(data).then(res => {
        if (res.code === 0) {
          this.$emit('refreshList')
        } else {
          this.$message.error(res.data.msg)
        }
      })
      this.$store.commit('ADD_CUSTOMER_STATUS_LIST', 'Normal')
      this.removeVisible = false
    },
    handleRemove(v) {
      this.removeType = v
      let text = v === 'black' ? '黑名单' : '特殊名单'
      this.remveText = `确定将这${this.selectedRowKeys.length}项移出${text}?`
      this.removeVisible = true
    },
    onChange(value, dateString) {
      // console.log('Selected Time: ', value)
      // console.log('Formatted Selected Time: ', dateString)
      this.search()
    },
    onOk(value) {
      console.log('onOk: ', value)
      // this.beginDate = value[0].format('YYYY-MM-DD HH:mm:ss')
      // this.endDate = value[1].format('YYYY-MM-DD HH:mm:ss')
      // console.log('startTime', this.beginDate)
      // console.log('endTime', this.endDate)
    },
    // 最高价
    gPriceChange(value) {
      console.log('changed', value)
    },
    // 最低价
    lPriceChange(value) {
      console.log('changed', value)
    },
    showModal(type, value) {
      if (value) {
        this.$emit('showModal', true, type)
      } else {
        this.$emit('showModal', false, type)
      }
    },
    search() {
      let queryParam = this.filterFields(this.queryParam)
      this.$emit('onSearch', queryParam)
    },
    reset() {
      this.queryParam = {
        // subStatus: '',
        // gender: '',
        fashionerId: '',
        // vipType: '',
        fashionerType: this.filter.fashionerType ? this.filter.fashionerType.filter(e => e.default)[0].code : null,
        reasonId: '',
        sortType: 1,
        phone: '',
        isBirthday: false
      }
      this.$refs.filterTree.resetSearchText()
      this.$refs.filterTree.resetFilter()

      // let queryParam = this.filterFields(this.queryParam)
      // this.$emit('onSearch', queryParam)
    },
    batchControl() {
      this.$message.warning('')
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined) {
          if (i === 'regTime') {
            formValue.regStartTime = values[i][0]
            formValue.regEndTime = values[i][1]
          } else if (i === 'subStartTime') {
            formValue.subStartStartTime = values[i][0]
            formValue.subStartEndTime = values[i][1]
          } else if (i === 'subEndTime') {
            formValue.subEndStartTime = values[i][0]
            formValue.subEndEndTime = values[i][1]
          } else if (i === 'joinTime') {
            formValue.joinStartTime = values[i][0]
            formValue.joinEndTime = values[i][1]
          } else if (i === 'isBirthday') {
            formValue.isHaveUnUsedBirthCoupon = values[i] ? 1 : 0
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    // 有可用生日折扣券
    switchChange(checked) {
      this.search()
    },
    handleChange(value) {
      this.search()
    },
    handleChangeType(value) {
      this.queryParam.salesPhone = ''
      this.queryParam.fashionerId = ''
      this.search()
    },
    // 筛选条件
    updateParams(baseData, highData) {
      let paramsArr = baseData ? JSON.parse(JSON.stringify(baseData)) : []
      let paramsHighArr = highData ? JSON.parse(JSON.stringify(highData)) : []
      if (paramsArr.length > 0) {
        // 会员卡等级
        this.queryParam.vipTypes = paramsArr.filter(e => e.title == '会员卡等级')[0].codes

        // BOX总消费金额
        let consumeAmount = paramsArr.filter(e => e.title == 'BOX总消费')[0]
        if (consumeAmount.codes.length > 0) {
          if (consumeAmount.codes[0] === '-1') {
            this.queryParam.consumeAmountMax = 0
            this.queryParam.consumeAmountMin = ''
          } else {
            this.queryParam.consumeAmountMin = consumeAmount.codes[0]
            this.queryParam.consumeAmountMax = ''
          }
        } else {
          this.queryParam.consumeAmountMin = ''
          this.queryParam.consumeAmountMax = ''
        }

        // 会员积分
        let customerPoint = paramsArr.filter(e => e.title == '会员积分')[0]
        if (customerPoint.isCustom && customerPoint.cusArr.length > 0) {
          this.queryParam.customerPointMin = Number(customerPoint.cusArr[0]) > -1 && customerPoint.cusArr[0] != null ? customerPoint.cusArr[0] : ''
          this.queryParam.customerPointMax = Number(customerPoint.cusArr[1]) > -1 && customerPoint.cusArr[1] != null ? customerPoint.cusArr[1] : ''
        } else {
          this.queryParam.customerPointMin = ''
          this.queryParam.customerPointMax = ''
        }
      }
      if (paramsHighArr.length > 0) {
        // 集团年消费金额
        let groupYearsConsume = paramsHighArr.filter(e => e.title == '集团年消费')[0]
        if (groupYearsConsume.isCustom && groupYearsConsume.cusArr.length > 0) {
          this.queryParam.groupYearsConsumeMin = Number(groupYearsConsume.cusArr[0]) > -1 && groupYearsConsume.cusArr[0] != null ? groupYearsConsume.cusArr[0] : ''
          this.queryParam.groupYearsConsumeMax = Number(groupYearsConsume.cusArr[1]) > -1 ? groupYearsConsume.cusArr[1] : ''
        } else {
          this.queryParam.groupYearsConsumeMin = ''
          this.queryParam.groupYearsConsumeMax = ''
        }

        // 上次消费距离今
        let lastConsumeToToday = paramsHighArr.filter(e => e.title == '上次消费')[0]
        if (lastConsumeToToday.codes.length > 0) {
          if (lastConsumeToToday.codes[0] == '-361') {
            this.queryParam.lastConsumeToTodayMin = '361'
            this.queryParam.lastConsumeToTodayMax = ''
          } else if (lastConsumeToToday.codes[0] == '-1') {
            this.queryParam.lastConsumeToTodayMin = ''
            this.queryParam.lastConsumeToTodayMax = '0'
          } else {
            this.queryParam.lastConsumeToTodayMax = lastConsumeToToday.codes[0]
            this.queryParam.lastConsumeToTodayMin = '0'
          }
        } else {
          this.queryParam.lastConsumeToTodayMax = ''
          this.queryParam.lastConsumeToTodayMin = ''
        }

        // 订阅状态
        let subStatus = paramsHighArr.filter(e => e.title == '订阅状态')[0]
        if (subStatus.codes.length > 0) {
          this.queryParam.userRightsStatus = parseInt(subStatus.codes[0])
        } else {
          this.queryParam.userRightsStatus = null
        }

        // 订阅来源
        this.queryParam.subTypes = paramsHighArr.filter(e => e.title == '订阅来源')[0].codes

        // 性别
        let gender = paramsHighArr.filter(e => e.title == '性别')[0]
        if (gender) {
          if (gender.codes.length > 0) {
            this.queryParam.gender = gender.codes[0]
          } else {
            this.queryParam.gender = ''
          }
        }
      }
      // console.log('updateParams', paramsArr, paramsHighArr)
      // console.log(this.queryParam)
      this.search()
    },
    updateSearchText(text) {
      this.queryParam.phone = text
      this.search()
    },
    // 剩余box
    updateRank(low, high) {
      this.queryParam.remainMin = low
      this.queryParam.remainMax = high
      this.search()
    },
    onChangePhone(e) {
      if (e.type == 'click') {
        this.searchSalesPhone()
      }
    },
    searchSalesPhone() {
      this.$refs.salesPhone.blur()
      this.search()
    }
  }
}
</script>
<style lang="less" scoped>
.table-page-search-submitButtons {
  display: flex;
  margin-bottom: 12px;
}
</style>

